<?php
/**
 * JSONRPCPresenter class definition
 * 
 * @author Sean Crystal <seancrystal@gmail.com>
 * @package MutantVole
 */  

/**
 * Base presenter extended to handle JSON-RPC requests
 * @package MutantVole
 * @subpackage Presenters
 */
class JSONRPCPresenter extends Presenter {
	/**
	 * Set a JSON-RPC response on the view
	 * @param string $id
	 * @param mixed $result
	 */
	protected function SetSuccessResponse($id, $result) {
		$this->view->MergeProperties(JSONRPC::GenerateResult($id, $result));
	}	
	
	/**
	 * Set a JSON-RPC error on the view
	 * @param string $id
	 * @param mixed $error
	 */
	protected function SetErrorResponse($id, $error) {
		$this->view->MergeProperties(JSONRPC::GenerateError($id, $error));
	}
	
	/**
	 * Handle SMD requests for this presenter. Bypasses the view because it is not a standard JSON-RPC reply.
	 */
	public function HandleSystemDescription() {
		echo JSONRPC::GenerateSMD($this, Dispatch::GetURL(array('mod' => $this->mod, 'page' => $this->page)));
		exit;
	}
	
	/**
	 * Overload function calls for JSON-RPC handler functions. HandleAction calls will be forwarded to
	 * JSONHandleAction requests. This is all mainly to make generating SMD easier. Normal request
	 * handler methods have a single array argument that contains all the request paramters. JSON-RPC 
	 * handler methods have individually specified arguments.
	 * @param string $name
	 * @param array $args
	 */
	public function __call($name, $args) {
		$matches = array();
		
		// translate HandleAction calls into JSONHandleAction calls
		if (preg_match('/^Handle(.+)$/', $name, $matches)) {
			$realName = "JSONHandle{$matches[1]}";
				
			if (method_exists($this, $realName)) {
				$jsonArgs = json_decode($args[0]['json-rpc']);
				
				$method = new ReflectionMethod(get_class($this), $realName);

				// assumes getParameters returns params in order
				foreach ($method->getParameters() as $i => $param) {
					if ($param->getName() != 'id') {
						$tmp[] = '$jsonArgs->params->'. $param->getName();
					}
				}
				
				eval('$this->$realName($jsonArgs->id, ' . implode(', ', $tmp) . ');');
			}
		}
	}
}

?>